<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm">
      <template #json="{ model, field }">
        <CodeEditor v-model:value="model[field]" mode="application/json" />
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { CodeEditor } from '/@/components/CodeEditor';
  import { formSchema } from './data';

  import { ModuleAdd, ModuleEdit, DefaultRule, AllWebsiteList } from '/@/api/demo/media';

  export default defineComponent({
    name: 'MediaModuleModal',
    components: { BasicModal, BasicForm, CodeEditor },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const rowId = ref('');

      const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          rowId.value = data.record.id;
          setFieldsValue({
            ...data.record,
          });
          setWebsite(data.record.group_id);
        } else {
          const rules = await DefaultRule();
          setFieldsValue({
            rules: JSON.stringify(rules),
          });
        }
      });
      async function setWebsite(group_id) {
        AllWebsiteList({ group_id: group_id }).then((res) => {
          const list = res;
          const websiteList = [];
          for (let i = 0; i < list.length; i++) {
            websiteList[i] = {
              label: list[i]['name'],
              value: list[i]['id'],
              key: list[i]['id'],
            };
          }
          console.log(list);
          console.log(websiteList);
          //赋值
          updateSchema({
            field: 'website_id',
            componentProps: {
              options: websiteList,
            },
          });
        });
      }
      const getTitle = computed(() => (!unref(isUpdate) ? '新增模块' : '编辑模块'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });
          // TODO custom api
          console.log(values);
          if (!unref(isUpdate)) {
            await ModuleAdd({ ...values });
          } else {
            await ModuleEdit({ ...values });
          }
          closeModal();
          emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, registerForm, getTitle, handleSubmit };
    },
  });
</script>
